const app = getApp()
//获得全局js变量
var util = require('../../../utils/util.js');
Page({
    data: {
        userInfo: {},
        user_nickname: '',
        user_avatar: '',
        url: 'https://www.zglianbang.com/api/miaozhimini/weixin/fileUpload' // 替换为你的实际URL
    },
    
    onLoad: function() {
        wx.setNavigationBarTitle({
            title: '个人资料'
        });
        
        const userInfo = app.globalData.userInfo;
		console.log(userInfo);
        this.setData({
            userInfo: userInfo,
            user_avatar: userInfo.userAvatar || '',
            user_nickname: userInfo.userNickname || ''
        });
    },
    
    onNicknameInput: function(e) {
        this.setData({
            user_nickname: e.detail.value
        });
    },
    
    chooseImage: function() {
        const that = this;
        wx.chooseImage({
            count: 1,
            success: function(res) {
                const tempFilePaths = res.tempFilePaths;
                that.setData({
                    user_avatar: tempFilePaths[0]
                });
                
                wx.showLoading({
                    title: '上传中',
                });
                
                wx.uploadFile({
                    url: that.data.url,
                    filePath: tempFilePaths[0],
                    header: {
                        'token': wx.getStorageSync('token')
                    },
                    name: 'file',
                    success: function(uploadRes) {
                        wx.hideLoading();
                        const data = JSON.parse(uploadRes.data);
                        that.setData({
                            user_avatar: data.data
                        });
                    },
                    fail: function(err) {
                        wx.hideLoading();
                        console.error('上传失败', err);
                    }
                });
            }
        });
    },
    
    save: function() {
        if (!this.data.user_nickname) {
            wx.showToast({
                icon: 'none',
                title: '请输入昵称'
            });
            return;
        }
        util.httpRrquest(app.data.rooturl + 'weixin/saveUser', 'POST',{'userAvatar':this.data.user_avatar,'userNickname':this.data.user_nickname,'isLogin':1})
        .then(function (response) {
            wx.showToast({
				icon: 'none',
				title: '保存成功'
			});
        }, function (error) {
            console.log(error);
        });
    }
});